package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import todo.MyTask;
import todo.TaskSet;
import tools.OptionReader;
import cal.MonthData;
import calendar.Event;
import calendar.EventSet;
import contacts.PersonSet;

/**
 * Klasse repräsentiert die Ansicht des Calenders
 * 
 * @author Michi
 * 
 */
public class CalView extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5115189270341846960L;

	/**
	 * Member Data
	 */
	private JTextField txtMonatNachher;
	private MonthData md;
	private JPanel calGroundPanel;
	private Date d;
	private CalView cv;
	private Test mainInstance;
	private int dayCount;
	private TaskSet ts;
	private PersonSet ps;
	private EventSet es;
	private Date clickedDay;
	@SuppressWarnings("unused")
	private Connection connection = null;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;

	// Sprachen (0 = deutsch; 1 = englisch; 2 = latein)
	int speak = 0;

	String[] kalender = { "Kalender", "Calendar", "Calendarium" };
	String[] kontakte = { "Kontakte", "Contacts", "Contactus" };
	String[] todo = { "Aufgabe", "Task", "Negotium" };
	String[] mail = { "E-Mail", "Mail", "Littersa" };
	String[] wochenansicht = { "Wochenansicht", "Weekview", "Hebdomadatim" };

	String[] toolTipLM = { "Zeigt vorherigen Monat an", "Show the last month.",
			"Ostendit priore mense" };
	String[] toolTipNM = { "Zeigt nächsten Monat an", "Show the next month.",
			"Ostendit proximo mense" };
	String[] toolTipAM = { "Hier wird Ihnen der aktuelle Monat dargestellt.",
			"Here you can see the current month.",
			"Hic vos ero ostendo occurrenti mensis" };
	String[] addEvent = { "Hier können sie einen neuen Termin hinzufügen",
			"Add a new event", "Hic adere nuovus terminus" };

	String[] januar = { "Januar", "January", "Ianiuarius" };
	String[] februar = { "Feburar", "February", "Februarius" };
	String[] maerz = { "März", "March", "Martius" };
	String[] april = { "April", "April", "Aprilis" };
	String[] mai = { "Mai", "May", "Maius" };
	String[] juni = { "Juni", "June", "Iunius" };
	String[] juli = { "Juli", "July", "Iulius" };
	String[] august = { "August", "August", "Augustus" };
	String[] september = { "September", "September", "September" };
	String[] oktober = { "Oktober", "October", "October" };
	String[] november = { "November", "November", "November" };
	String[] dezember = { "Dezember", "December", "December" };

	String[] mo = { "Mo., ", "Mo., ", "Lu., " };
	String[] di = { "Di., ", "Tu., ", "Ma., " };
	String[] mi = { "Mi., ", "We., ", "Me., " };
	String[] don = { "Do., ", "Th., ", "Io., " };
	String[] fr = { "Fr., ", "Fr., ", "Ve., " };
	String[] sa = { "Sa., ", "Sa., ", "Sa., " };
	String[] so = { "So., ", "Su., ", "So., " };

	String[] weitererTermin = { " weiteres Ereigniss", " more event",
			" plus eventuum" };
	String[] weitereTermine = { " weitere Ereignisse", " more events",
			" plus eventi" };

	public int getDayCount() {
		return dayCount;
	}

	public void setDayCount(int dayCount) {
		this.dayCount = dayCount;
	}

	public Test getMainInstance() {
		return mainInstance;
	}

	public void setMainInstance(Test mainInstance) {
		this.mainInstance = mainInstance;
	}

	public CalView getCv() {
		return cv;
	}

	public void setCv(CalView cv) {
		this.cv = cv;
	}

	public Date getD() {
		return d;
	}

	public void setD(Date d) {
		this.d = d;
	}

	private JScrollPane calGroundPanelScrollPane;
	private JPanel buttonPanel;
	private JButton newEventButton;
	private JButton switchViewButton;
	private JButton backButton;
	private JButton forButton;
	private JButton dummyButton;

	// Setter & Getter
	public JTextField getTxtMonatNachher() {
		return txtMonatNachher;
	}

	public void setTxtMonatNachher(JTextField txtMonatNachher) {
		this.txtMonatNachher = txtMonatNachher;
	}

	public TaskSet getTs() {
		return ts;
	}

	public void setTs() {
		this.ts = new TaskSet();
	}

	public EventSet getEs() {
		return es;
	}

	public void setEs() {
		this.es = new EventSet();
	}

	/**
	 * Konstruktor Create the panel.
	 * 
	 * @wbp.parser.constructor
	 */
	public CalView(Test test) {
		init(test);

		createCal(d);

	}

	/**
	 * Konstruktor
	 * 
	 * @param test
	 *            Hauptinstanz
	 * @param clicked
	 *            Datum auf das zuletzt geklickt wurde
	 */
	public CalView(Test test, Date clicked) {
		init(test);

		createCal(clicked, clicked);
	}

	/**
	 * Stellt basisfunktionen bereit
	 * 
	 * @param test
	 */
	public void init(Test test) {
		// Initialisierung
		md = new MonthData();
		d = new Date();
		cv = this;
		mainInstance = test;
		ts = new TaskSet();
		ps = new PersonSet();
		es = new EventSet();
		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		speak = Integer.parseInt(or.getLanguage());

		connection = Test.getConnection();

		setLayout(new BorderLayout(0, 0));

		// Start Button
		// Panel---------------------------------------------------------

		buttonPanel = new JPanel();
		buttonPanel.setBackground(new Color(r, g, b));
		buttonPanel.setSize(new Dimension(260, 40));
		buttonPanel.setMinimumSize(new Dimension(260, 40));
		buttonPanel.setMaximumSize(new Dimension(260, 40));
		buttonPanel.setPreferredSize(new Dimension(260, 40));
		add(buttonPanel, BorderLayout.NORTH);
		GridBagLayout gbl_buttonPanel = new GridBagLayout();
		gbl_buttonPanel.columnWidths = new int[] { 80, 110, 140, 0, 0, 0, 0 };
		gbl_buttonPanel.rowHeights = new int[] { 0, 0 };
		gbl_buttonPanel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 1.0,
				0.0, Double.MIN_VALUE };
		gbl_buttonPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		buttonPanel.setLayout(gbl_buttonPanel);

		Icon iconAdd = new ImageIcon("src/pictures/add.png");
		newEventButton = new JButton(iconAdd);
		newEventButton.setToolTipText(addEvent[speak]);
		newEventButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				new NewEventWindow(cv).setVisible(true);
			}
		});
		newEventButton.setMaximumSize(new Dimension(40, 40));
		newEventButton.setMinimumSize(new Dimension(40, 40));
		newEventButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_newEventButton = new GridBagConstraints();
		gbc_newEventButton.fill = GridBagConstraints.HORIZONTAL;
		gbc_newEventButton.insets = new Insets(0, 0, 0, 5);
		gbc_newEventButton.gridx = 0;
		gbc_newEventButton.gridy = 0;
		buttonPanel.add(newEventButton, gbc_newEventButton);

		Icon iconSwitch = new ImageIcon("src/pictures/zurWochenAnsicht.png");
		switchViewButton = new JButton(iconSwitch);
		switchViewButton.setToolTipText(wochenansicht[speak]);
		switchViewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				mainInstance.setProgressBarVisibleTrue();

				mainInstance.getTabbedPane().removeTabAt(0);
				if (clickedDay == null) {
					mainInstance.setKalender(new WeekView(mainInstance, d));
				} else {
					mainInstance.setKalender(new WeekView(mainInstance,
							getClickedDay()));
				}

				mainInstance.getTabbedPane().add(mainInstance.getKalender(),
						kalender[speak]);

				mainInstance.getTabbedPane().remove(mainInstance.getKontakte());
				mainInstance.setKontakte(new AddContactPane());
				mainInstance.getTabbedPane().add(mainInstance.getKontakte(),
						kontakte[speak]);

				mainInstance.getTabbedPane().remove(mainInstance.getToDo());
				mainInstance.setToDo(new ToDoPane());
				mainInstance.getTabbedPane().add(mainInstance.getToDo(),
						todo[speak]);

				mainInstance.getTabbedPane().remove(mainInstance.getViewMail());
				mainInstance.setViewMail(new ViewMail(mainInstance));
				mainInstance.getTabbedPane().add(mainInstance.getViewMail(),
						mail[speak]);
				mainInstance.setProgressBarVisibleFalse();
			}
		});
		switchViewButton.setMaximumSize(new Dimension(40, 40));
		switchViewButton.setMinimumSize(new Dimension(40, 40));
		switchViewButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_switchViewButton = new GridBagConstraints();
		gbc_switchViewButton.fill = GridBagConstraints.HORIZONTAL;
		gbc_switchViewButton.insets = new Insets(0, 0, 0, 5);
		gbc_switchViewButton.gridx = 1;
		gbc_switchViewButton.gridy = 0;
		buttonPanel.add(switchViewButton, gbc_switchViewButton);

		dummyButton = new JButton("dummy");
		dummyButton.setVisible(false);
		GridBagConstraints gbc_dummyButton = new GridBagConstraints();
		gbc_dummyButton.insets = new Insets(0, 0, 0, 5);
		gbc_dummyButton.gridx = 2;
		gbc_dummyButton.gridy = 0;
		buttonPanel.add(dummyButton, gbc_dummyButton);

		Icon iconBack = new ImageIcon("src/pictures/last.png");
		backButton = new JButton(iconBack);
		backButton.setToolTipText(toolTipLM[speak]);
		backButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mainInstance.setProgressBarVisibleTrue();
				d = minusMonth(d);
				calGroundPanelScrollPane.setViewportView(null);
				createCal(d);
				calGroundPanelScrollPane.setViewportView(getCalGroundPanel());
				mainInstance.setProgressBarVisibleFalse();
			}
		});
		backButton.setPreferredSize(new Dimension(40, 40));
		backButton.setMinimumSize(new Dimension(40, 40));
		backButton.setMaximumSize(new Dimension(40, 40));
		GridBagConstraints gbc_backButton = new GridBagConstraints();
		gbc_backButton.insets = new Insets(0, 0, 0, 5);
		gbc_backButton.gridx = 3;
		gbc_backButton.gridy = 0;
		buttonPanel.add(backButton, gbc_backButton);

		txtMonatNachher = new JTextField();
		txtMonatNachher.setToolTipText(toolTipAM[speak]);
		txtMonatNachher.setPreferredSize(new Dimension(50, 28));
		GridBagConstraints gbc_textField = new GridBagConstraints();
		gbc_textField.insets = new Insets(0, 0, 0, 5);
		gbc_textField.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField.gridx = 4;
		gbc_textField.gridy = 0;
		txtMonatNachher.setColumns(10);
		txtMonatNachher.setHorizontalAlignment(SwingConstants.CENTER);
		txtMonatNachher.setToolTipText(toolTipAM[speak]);
		txtMonatNachher.setDisabledTextColor(new Color(0, 0, 0));
		txtMonatNachher.setEnabled(false);
		txtMonatNachher.setEditable(false);
		buttonPanel.add(txtMonatNachher, gbc_textField);

		Icon iconNext = new ImageIcon("src/pictures/next.png");
		forButton = new JButton(iconNext);
		forButton.setToolTipText(toolTipNM[speak]);
		forButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mainInstance.setProgressBarVisibleTrue();
				d = plusMonth(d);
				calGroundPanelScrollPane.setViewportView(null);
				createCal(d);
				calGroundPanelScrollPane.setViewportView(getCalGroundPanel());
				mainInstance.setProgressBarVisibleFalse();
			}
		});
		forButton.setMaximumSize(new Dimension(40, 40));
		forButton.setMinimumSize(new Dimension(40, 40));
		forButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_forButton = new GridBagConstraints();
		gbc_forButton.gridx = 5;
		gbc_forButton.gridy = 0;
		buttonPanel.add(forButton, gbc_forButton);

		// Ende-Button-Panel---------------------------------------------------------

		// Erstellung des Untergrund Panels für den Kalender
		setCalGroundPanel(new JPanel());
		getCalGroundPanel().setBackground(Color.GRAY);
		calGroundPanelScrollPane = new JScrollPane(getCalGroundPanel());
		add(calGroundPanelScrollPane, BorderLayout.CENTER);
		getCalGroundPanel().setLayout(new GridLayout(6, 7, 6, 7));
	}

	public JScrollPane getCalGroundPanelScrollPane() {
		return calGroundPanelScrollPane;
	}

	public void setCalGroundPanelScrollPane(JScrollPane calGroundPanelScrollPane) {
		this.calGroundPanelScrollPane = calGroundPanelScrollPane;
	}

	/**
	 * Schneller Skalierer für Bilder
	 * 
	 * @param ret
	 *            Bild welches skaliert werden soll
	 * @param w
	 *            neue Breite
	 * @param h
	 *            neue Höhe
	 * @return Bild mit neuer Breite & Höhe
	 */
	public Image resize(Image ret, int w, int h) {

		BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = tmp.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2.drawImage(ret, 0, 0, w, h, null);
		g2.dispose();
		return tmp;
	}

	/**
	 * Umwandlung von Integer Zahl in den String des zugehörigen Monats
	 * 
	 * @param i
	 *            Integer als Monat
	 * @return String Monatsname
	 */
	public String intToMonth(int i) {
		String str = "";
		switch (i) {

		case 0:
			str = januar[speak];
			break;
		case 1:
			str = februar[speak];
			break;
		case 2:
			str = maerz[speak];
			break;
		case 3:
			str = april[speak];
			break;
		case 4:
			str = mai[speak];
			break;
		case 5:
			str = juni[speak];
			break;
		case 6:
			str = juli[speak];
			break;
		case 7:
			str = august[speak];
			break;
		case 8:
			str = september[speak];
			break;
		case 9:
			str = oktober[speak];
			break;
		case 10:
			str = november[speak];
			break;
		case 11:
			str = dezember[speak];
			break;
		}
		return str;
	}

	/**
	 * Erstellt dynamisch die Kalendermonatsansicht
	 * 
	 * @param d
	 *            Datum des Monats der angezeigt werden soll
	 */
	@SuppressWarnings({ "deprecation", "static-access", "unchecked" })
	// TODO
	public void createCal(final Date d) {// TODO

		getCalGroundPanel().removeAll();
		Date[] da = md.getDateArray(d);
		int[] ia = md.getIntArray(d);
		Boolean[] ba = md.getBoolArray(d);

		for (int i = 0; i < da.length; i++) {

			final DayPanel dp;
			dp = new DayPanel();

			// New
			List<Event> eventList = new ArrayList<Event>();
			List<String[]> gebList = new ArrayList<String[]>();
			List<MyTask> taskList = new ArrayList<MyTask>();
			List<String> termine = new ArrayList<String>();
			List<Integer> typen = new ArrayList<Integer>();
			// New

			// Setzen von Informationen
			dp.setColored(ba[i]);
			dp.setDate(da[i]);

			// new

			try {
				eventList = es.getTasks(es.getResultSet(), dp.getDate());
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (SQLException e1) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			try {
				taskList = ts.getTasks(ts.getResultSet(), dp.getDate());

			} catch (NumberFormatException e2) {
				e2.printStackTrace();
			} catch (SQLException e2) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			}

			try {
				gebList = ps.getTasks(ps.getResultSet(), dp.getDate());

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			}

			String termin1 = "";
			String termin2 = "";
			int termincount = 0;

			// new
			for (int j = 0; j < eventList.size(); j++) {

				termine.add(eventList.get(j).getName());
				termincount++;
				typen.add(1);
			}

			for (int j = 0; j < gebList.size(); j++) {
				String name = "";
				String[] datas = gebList.get(j);

				String vorname = datas[0];

				String alter = datas[2];
				if (vorname != "") {
					name = vorname;
				}

				if (datas[1] != null) {
					Character nachname = datas[1].charAt(0);
					name = vorname + " " + nachname + ".";
				}

				name += " (" + alter + ")";
				termine.add(name);
				typen.add(2);
				termincount++;

			}

			for (int j = 0; j < taskList.size(); j++) {
				termine.add(taskList.get(j).getName());
				System.out.println(taskList.get(j).getName());
				termincount++;
				typen.add(3);
			}

			if (termine.size() > 0) {
				termin1 = termine.get(0);
				if (termine.size() > 1) {
					termin2 = termine.get(1);
				}
			}

			String tooltip = "<html>";
			for (int j = 2; j < termine.size(); j++) {
				tooltip = tooltip + termine.get(j) + "<br>";
			}
			tooltip = tooltip + " </html>";

			dp.getMoreField().setToolTipText(tooltip);

			dp.getAllCalendarItems().addAll(eventList);
			dp.getAllCalendarItems().addAll(taskList);
			dp.getAllCalendarItems().addAll(gebList);

			if (i == 0) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(mo[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 1) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(di[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 2) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(mi[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 3) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(don[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 4) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(fr[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 5) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(sa[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 6) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(so[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}

			if (i < 7) {

			} else {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText("" + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}

			// Daten eingelesen

			dp.getTermin1().setText(termin1);
			dp.getTermin2().setText(termin2);

			if (termincount > 2) {
				dp.getMoreField().setVisible(true);
				dp.getMoreField().setBackground(Color.WHITE);
				if (termincount == 3) {
					dp.getMoreField().setText(
							termincount - 2 + weitererTermin[speak]);
				} else {
					dp.getMoreField().setText(
							termincount - 2 + weitereTermine[speak]);
				}
			}

			if (!dp.getColored()) {
				dp.getNorthPanel().setBackground(Color.LIGHT_GRAY);
				dp.getNameOfDayPanel().setBackground(Color.LIGHT_GRAY);
				dp.getButtonPanel().setBackground(Color.LIGHT_GRAY);
				dp.getTerminPanel().setBackground(Color.LIGHT_GRAY);
				dp.getNameOfDayField().setBackground(Color.LIGHT_GRAY);
				dp.getTermin1().setBackground(Color.LIGHT_GRAY);
				dp.getTermin2().setBackground(Color.LIGHT_GRAY);
				dp.getHinzufuegenButton().setVisible(false);

			}

			getTxtMonatNachher().setText(
					intToMonth(d.getMonth()) + " " + (d.getYear() + 1900));

			dp.getHinzufuegenButton().addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					new NewEventWindow(dp.getDate(), cv).setVisible(true);

				}

			});

			Date today = getSimpleDate();
			if (dp.getDate().equals(today)) {
				dp.getNorthPanel().setBackground(SystemColor.window);
				dp.getNameOfDayPanel().setBackground(SystemColor.window);
				dp.getButtonPanel().setBackground(SystemColor.window);
				dp.getTerminPanel().setBackground(SystemColor.window);
				dp.getNameOfDayField().setBackground(SystemColor.window);
				dp.getTermin1().setBackground(SystemColor.window);
				dp.getTermin2().setBackground(SystemColor.window);
				dp.getMoreField().setBackground(SystemColor.window);
				setDayCount(termincount);

			}

			if (dp.getColored()) {
				if (termincount > 0) {
					if (typen.get(0) == 2) {
						dp.getTermin1().setBackground(new Color(255, 255, 204));

					}
					if (typen.get(0) == 3) {
						dp.getTermin1().setBackground(new Color(205, 205, 193));
					}
				}
				if (termincount > 1) {
					if (typen.get(1) == 2) {
						dp.getTermin2().setBackground(new Color(255, 255, 204));

					}
					if (typen.get(1) == 3) {
						dp.getTermin2().setBackground(new Color(205, 205, 193));

					}
				}
			}

			dp.getNorthPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());

				}
			});
			dp.getNameOfDayPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());

				}
			});
			dp.getButtonPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());
				}
			});
			dp.getTerminPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());
				}
			});
			dp.getNameOfDayField().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());
				}
			});
			dp.getTermin1().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());
				}
			});
			dp.getTermin2().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());
				}
			});
			dp.getMoreField().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					calGroundPanelScrollPane.setViewportView(null);
					createCal(dp.getDate(), dp.getDate());
					calGroundPanelScrollPane
							.setViewportView(getCalGroundPanel());
					setD(dp.getDate());
				}
			});

			getCalGroundPanel().add(dp);

		}

	}

	/**
	 * Erhöht ein übergebenes Datum um einen Monat
	 * 
	 * @param d
	 *            Datum dass übergeben wird
	 * @return neues Datum erhöht um einen Monat
	 */
	@SuppressWarnings("deprecation")
	public Date plusMonth(Date d) {
		int y = d.getYear();
		int m = d.getMonth();
		int t = d.getDate();
		m++;
		return new Date(y, m, t);
	}

	/**
	 * verrringert ein übergebenes Datum um einen Monat
	 * 
	 * @param d
	 *            Datum dass übergeben wird
	 * @return neues Datum verringert um einen Monat
	 */
	@SuppressWarnings("deprecation")
	public Date minusMonth(Date d) {
		int y = d.getYear();
		int m = d.getMonth();
		int t = d.getDate();
		m--;
		return new Date(y, m, t);
	}

	/**
	 * Gibt aktuelles Datum in bestimter ansicht zurück
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public Date getSimpleDate() {
		int y = new Date().getYear();
		int m = new Date().getMonth();
		int t = new Date().getDate();
		return new Date(y, m, t);
	}

	/**
	 * Konstruktor
	 * 
	 * @param d
	 *            Datum des Monats zu dem Ansicht generiert werden soll
	 * @param click
	 *            Datum das zuletzt angeklickt wurde
	 */
	@SuppressWarnings({ "deprecation", "static-access", "unchecked" })
	public void createCal(final Date d, Date click) {

		setClickedDay(click);
		getCalGroundPanel().removeAll();
		Date[] da = md.getDateArray(d);
		int[] ia = md.getIntArray(d);
		Boolean[] ba = md.getBoolArray(d);
		setClickedDay(click);

		for (int i = 0; i < da.length; i++) {

			final DayPanel dp;
			dp = new DayPanel();

			// New
			List<Event> eventList = new ArrayList<Event>();
			List<String[]> gebList = new ArrayList<String[]>();
			List<MyTask> taskList = new ArrayList<MyTask>();
			List<String> termine = new ArrayList<String>();
			List<Integer> typen = new ArrayList<Integer>();
			// New

			// Setzen von Informationen
			dp.setColored(ba[i]);
			dp.setDate(da[i]);

			try {
				eventList = es.getTasks(es.getResultSet(), dp.getDate());
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (SQLException e1) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			try {
				taskList = ts.getTasks(ts.getResultSet(), dp.getDate());

			} catch (NumberFormatException e2) {
				e2.printStackTrace();
			} catch (SQLException e2) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			}

			try {
				gebList = ps.getTasks(ps.getResultSet(), dp.getDate());

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			}

			String termin1 = "";
			String termin2 = "";
			int termincount = 0;

			// new
			for (int j = 0; j < eventList.size(); j++) {
				termine.add(eventList.get(j).getName());
				termincount++;
				typen.add(1);
			}

			for (int j = 0; j < gebList.size(); j++) {
				String name = "";
				String[] datas = gebList.get(j);

				String vorname = datas[0];

				String alter = datas[2];
				if (vorname != "") {
					name = vorname;
				}

				if (datas[1] != null) {
					Character nachname = datas[1].charAt(0);
					name = vorname + " " + nachname + ".";
				}
				name += " (" + alter + ")";
				termine.add(name);
				typen.add(2);
				termincount++;

			}

			for (int j = 0; j < taskList.size(); j++) {
				termine.add(taskList.get(j).getName());
				System.out.println(taskList.get(j).getName());
				termincount++;
				typen.add(3);
			}

			if (termine.size() > 0) {
				termin1 = termine.get(0);
				if (termine.size() > 1) {
					termin2 = termine.get(1);
				}
			}

			String tooltip = "<html>";
			for (int j = 2; j < termine.size(); j++) {
				tooltip = tooltip + termine.get(j) + "<br>";
			}
			tooltip = tooltip + " </html>";

			dp.getMoreField().setToolTipText(tooltip);

			dp.getAllCalendarItems().addAll(eventList);
			dp.getAllCalendarItems().addAll(taskList);
			dp.getAllCalendarItems().addAll(gebList);

			if (i == 0) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(mo[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 1) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(di[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 2) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(mi[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 3) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(don[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 4) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(fr[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 5) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(sa[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}
			if (i == 6) {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText(so[speak] + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}

			if (i < 7) {

			} else {
				dp.getNameOfDayField().setVisible(true);
				dp.getNameOfDayField().setText("" + ia[i]);
				dp.getNameOfDayField().setCaretPosition(0);
			}

			// Daten eingelesen

			dp.getTermin1().setText(termin1);
			dp.getTermin2().setText(termin2);

			if (termincount > 2) {
				dp.getMoreField().setVisible(true);
				dp.getMoreField().setBackground(Color.WHITE);
				if (termincount == 3) {
					dp.getMoreField().setText(
							termincount - 2 + weitererTermin[speak]);
				} else {
					dp.getMoreField().setText(
							termincount - 2 + weitereTermine[speak]);
				}
			}

			if (!dp.getColored()) {
				dp.getNorthPanel().setBackground(Color.LIGHT_GRAY);
				dp.getNameOfDayPanel().setBackground(Color.LIGHT_GRAY);
				dp.getButtonPanel().setBackground(Color.LIGHT_GRAY);
				dp.getTerminPanel().setBackground(Color.LIGHT_GRAY);
				dp.getNameOfDayField().setBackground(Color.LIGHT_GRAY);
				dp.getTermin1().setBackground(Color.LIGHT_GRAY);
				dp.getTermin2().setBackground(Color.LIGHT_GRAY);
				dp.getHinzufuegenButton().setVisible(false);

			}

			getTxtMonatNachher().setText(
					intToMonth(d.getMonth()) + " " + (d.getYear() + 1900));

			dp.getHinzufuegenButton().addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					new NewEventWindow(dp.getDate(), cv).setVisible(true);

				}

			});

			Date today = getSimpleDate();
			if (dp.getDate().equals(today)) {
				dp.getNorthPanel().setBackground(SystemColor.window);
				dp.getNameOfDayPanel().setBackground(SystemColor.window);
				dp.getButtonPanel().setBackground(SystemColor.window);
				dp.getTerminPanel().setBackground(SystemColor.window);
				dp.getNameOfDayField().setBackground(SystemColor.window);
				dp.getTermin1().setBackground(SystemColor.window);
				dp.getTermin2().setBackground(SystemColor.window);
				dp.getMoreField().setBackground(SystemColor.window);
				setDayCount(termincount);

			}

			if (dp.getColored()) {
				if (termincount > 0) {
					if (typen.get(0) == 2) {
						dp.getTermin1().setBackground(new Color(255, 255, 204));

					}
					if (typen.get(0) == 3) {
						dp.getTermin1().setBackground(new Color(205, 205, 193));
					}
				}
				if (termincount > 1) {
					if (typen.get(1) == 2) {
						dp.getTermin2().setBackground(new Color(255, 255, 204));

					}
					if (typen.get(1) == 3) {
						dp.getTermin2().setBackground(new Color(205, 205, 193));

					}
				}
			}

			if (dp.getDate().equals(click)) {
				if (click != null) {
					dp.setSelected(true);
					dp.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
					dp.getNorthPanel().setBackground(Color.WHITE);
					dp.getNameOfDayPanel().setBackground(Color.WHITE);
					dp.getButtonPanel().setBackground(Color.WHITE);
					dp.getTerminPanel().setBackground(Color.WHITE);
					dp.getNameOfDayField().setBackground(Color.WHITE);
					dp.getTermin1().setBackground(Color.WHITE);
					dp.getTermin2().setBackground(Color.WHITE);
					dp.getMoreField().setBackground(Color.WHITE);
				}
			}

			dp.getNorthPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {

					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getNameOfDayPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getButtonPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);
					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getTerminPanel().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getNameOfDayField().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getTermin1().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getTermin2().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});
			dp.getMoreField().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (dp.isSelected()) {
						new DayView(cv, dp).setVisible(true);

					} else {

						calGroundPanelScrollPane.setViewportView(null);
						createCal(dp.getDate(), dp.getDate());
						calGroundPanelScrollPane
								.setViewportView(getCalGroundPanel());
						setD(dp.getDate());

					}
				}
			});

			getCalGroundPanel().add(dp);

		}

	}

	/**
	 * Wandelt Datum in String um
	 * 
	 * @param date
	 *            Datum das gewandelt werden soll
	 * @return String des Datums
	 */
	@SuppressWarnings("deprecation")
	public String DateToString(Date date) {
		String str = "";
		String a = "";
		if (date.getDate() < 10) {
			a = "0" + date.getDate();
		} else {
			a = "" + date.getDate();
		}

		String b = "";
		if (date.getMonth() < 9) {
			String s = (date.getMonth() + 1) + "";
			b = ("0" + s);
		} else {
			b = (date.getMonth() + 1) + "";
		}

		String c = (date.getYear() + 1900) + "";

		str = c + "-" + b + "-" + a;

		return str;

	}

	/**
	 * Generiert Datum aus String
	 * 
	 * @param Date
	 *            Datum das gewandelt werden soll
	 * @return Datum des Strings
	 */
	public Date StringToDate(String Date) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date ret;
		try {
			ret = sdf.parse(Date);
			return ret;
		} catch (ParseException e) {

			e.printStackTrace();
			return null;
		}

	}

	/**
	 * Stellt verbindung zur Datenbank her
	 * 
	 * @return
	 */
	// public boolean connect() {
	//
	// try {
	// Class.forName("com.mysql.jdbc.Driver");
	// connection = DriverManager
	// .getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
	//
	// } catch (ClassNotFoundException e) {
	//
	// e.printStackTrace();
	// } catch (SQLException e) {
	// JOptionPane.showMessageDialog(null,
	// "Es konnte keine Verbindung zur Datenbank hergestellt werden",
	// "Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
	// e.printStackTrace();
	// return false;
	// }
	//
	// return true;
	// }

	public JPanel getCalGroundPanel() {
		return calGroundPanel;
	}

	public void setCalGroundPanel(JPanel calGroundPanel) {
		this.calGroundPanel = calGroundPanel;
	}

	public Date getClickedDay() {
		return clickedDay;
	}

	public void setClickedDay(Date clickedDay) {
		this.clickedDay = clickedDay;
	}

}
